/**********************************************************************
 * SailmiPIM - modular cross-platform feature Personal Information Manager Tools.
 * Copyright(C) 2006-2014  Georg Rudoy
 *
 * Distributed under the Boost Software License, Version 1.0.
 *(See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
 **********************************************************************/

#include "splashscreen.h"
#include <QStyle>
#include <QApplication>
#include <QStyleOptionProgressBar>
#include <qprogressbar.h>
#include "loadprocessbase.h"

namespace SailmiPIM
{
	void SplashScreen::RegisterLoadProcess(LoadProcessBase *proc)
	{
        qDebug() << Q_FUNC_INFO << "Register PluginLoadProcess " << proc->GetTitle();

		Processes_ << proc;
        //repaint();
        update();
        qDebug() << Q_FUNC_INFO << "Register PluginLoadProcess Connect Evecnt " << proc->GetTitle();

		connect(proc,
				&LoadProcessBase::changed,
				this,
				&SplashScreen::repaint);
		connect(proc,
				&QObject::destroyed,
				this,
				[this, proc]
				{
					Processes_.removeOne(proc);
                    update();
				});
        qDebug() << Q_FUNC_INFO << "Register PluginLoadProcess finish " << proc->GetTitle();

	}

	void SplashScreen::drawContents(QPainter *painter)
	{
		QSplashScreen::drawContents(painter);

		const auto margin = 10;
		int ypos = margin;
		const auto height = 1.3 * fontMetrics().height();

		QStyleOptionProgressBar opt;
		opt.initFrom(this);
		opt.rect.setWidth(width());
		opt.rect.setHeight(height);
        opt.state = QStyle::StateFlag::State_Horizontal;
		opt.textVisible = true;

		constexpr QColor lcOrange { 0xFF, 0x3B, 0x00 };
		constexpr QColor contrastingDark { 0x1B, 0x18, 0x1F };
		auto& p = opt.palette;
		p.setColor(QPalette::Base, Qt::transparent);
		p.setColor(QPalette::Window, Qt::transparent);
		p.setColor(QPalette::Highlight, lcOrange);
		p.setColor(QPalette::Text, lcOrange);
		p.setColor(QPalette::WindowText, lcOrange);
		p.setColor(QPalette::HighlightedText, contrastingDark);

		for(const auto proc : Processes_)
		{
			opt.rect.moveTop(ypos);
			ypos += height;

			opt.minimum = proc->GetMin();
			opt.maximum = proc->GetMax();
			opt.progress = proc->GetValue();
			opt.text = proc->GetTitle() + " " + tr("(%1 of %2)").arg(opt.progress).arg(opt.maximum);
            //qDebug() << Q_FUNC_INFO << opt.text;
            QProgressBar qbar;
            this->style()->drawControl(QStyle::CE_ProgressBar, &opt, painter,&qbar);
            //qDebug() << Q_FUNC_INFO << "Draw Control end!";
		}
	}
}
